package com.code.generate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName CodeTemplateGenerator
 * @Description 代码模板生成器，把固定的代码，设置变量去替换代码中的字符，从而形成代码模板，用于代码生成器
 * @author simple
 * @date 2017年4月13日 下午2:08:27
 */
public class CodeTemplateGenerator {

	public List<File> getAllCodeFile(File pathFile) {
		List<File> files = new ArrayList<>();
		if (pathFile.isDirectory()) {
			File[] listFile = pathFile.listFiles();
			for (File file : listFile) {
				files.addAll(this.getAllCodeFile(file));
			}
		} else {
			files.add(pathFile);
		}
		return files;
	}

	/**
	 * @Title: read
	 * @Description: 读取文件内容
	 * @param file
	 * @return
	 * @Return String
	 */
	public String read(File file) {
		try (RandomAccessFile fileReader = new RandomAccessFile(file, "r");) {
			byte[] b = new byte[(int) file.length()];
			fileReader.seek(0L);
			fileReader.read(b);
			return new String(b);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	public static void main(String[] args) throws IOException {

		String codePath = "E:/tmp/code";

		String templatePath = "E:/tmp/template/test";

		List<String[]> replacements = new ArrayList<>();
		replacements.add(new String[] { "Message", "@{模块功能名}" });
		replacements.add(new String[] { "message", "@{小写模块功能名}" });
		replacements.add(new String[] { "cn.com.servyou.gzyjzx.frame", "@{基础包名}" });
		replacements.add(new String[] { "example.xxzx", "@{模块包名}" });

		CodeTemplateGenerator ctg = new CodeTemplateGenerator();

		List<File> files = ctg.getAllCodeFile(new File(codePath));
		for (File file : files) {
			System.out.println("===============================================");
			String templateFile = file.getAbsolutePath().replaceAll("\\\\", "/").replaceAll(codePath, templatePath);

			String templateFileContent = ctg.read(file);

			for (String[] strings : replacements) {
				templateFile = templateFile.replaceAll(strings[0], strings[1]);
				templateFileContent = templateFileContent.replaceAll(strings[0], strings[1]);
			}

			ctg.createTemplateFile(templateFile, templateFileContent);

			System.out.println(templateFile);
			System.out.println(templateFileContent);
		}

	}

	private void createTemplateFile(String templateFile, String templateFileContent) throws IOException {
		File file = new File(templateFile);
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		FileOutputStream fos;
		if (!file.exists()) {
			file.createNewFile();
		}
		fos = new FileOutputStream(file);
		Writer out = new OutputStreamWriter(fos, "UTF-8");
		out.write(templateFileContent);
		out.close();
		fos.close();
	}

}
